﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using UwinEducation.Application.Common.Helpers;
using UwinEducation.Application.Dtos;
using UwinEducation.Application.Extensions;
using UwinEducation.Domain.Entities;
using UwinEducation.Shared.Enums;

namespace UwinEducation.Application.Mappings
{
    public class StudentProfile : Profile
    {
        public StudentProfile()
        {
            // int _year = ServiceLocator.GetConfigIntValue("grade11Month", 10); // 默认10月
            // int _month = ServiceLocator.GetConfigIntValue("grade11Data", 1);  // 默认1日

            CreateMap<Student, StudentDto>()
                .ForMember(dest => dest.Grade, opt => opt.MapFrom<GradeResolver>());

            //CreateMap<RolePermission, RolePermission>();
            //student.Grade = student.Grade.GetGradeByEnrollmentDate(student.EnrollmentDate);

            CreateMap<CreateStudentDto, Student>();
            CreateMap<UpdateStudentDto, Student>();
        }
    }

    // 将解析器移到类外部
    public class GradeResolver : IValueResolver<Student, StudentDto, GradeEnum?>
    {
        // 静态缓存配置值
        private static int? _cachedMonth = null;
        private static int? _cachedDay = null;
        private static DateTime _lastCacheTime = DateTime.MinValue;
        private static readonly TimeSpan _cacheExpiration = TimeSpan.FromSeconds(10);

        public GradeEnum? Resolve(
            Student source,
            StudentDto destination,
            GradeEnum? destMember,
            ResolutionContext context
        )
        {
            // 获取缓存的配置值
            GetCachedConfigValues(out int month, out int day);
            return source.Grade.GetGradeByEnrollmentDate(source.EnrollmentDate, month, day);
        }

        // 获取缓存的配置值
        private static void GetCachedConfigValues(out int month, out int day)
        {
            // 检查缓存是否过期
            if (
                _cachedMonth == null
                || _cachedDay == null
                || DateTime.Now - _lastCacheTime > _cacheExpiration
            )
            {
                // 从配置中获取值
                _cachedMonth = ServiceLocator.GetConfigIntValue("grade11Month", 10);
                _cachedDay = ServiceLocator.GetConfigIntValue("grade11Data", 1);
                _lastCacheTime = DateTime.Now;
            }
            month = _cachedMonth.Value;
            day = _cachedDay.Value;
        }
    }
}
